from tortoise.exceptions import DoesNotExist

from common.utils import get_password_hash
from common.utils import verify_password
from common.utils import create_access_token
from common.utils import payload_token
from dao.user import user_dao
from schemas import Response


class UserService:

    @classmethod
    async def current_user(cls, obj):
        """当前用户信息"""
        return Response(data=obj)

    @classmethod
    async def get(cls, pk: int):
        try:
            return Response(data=await user_dao.get(id=pk))
        except DoesNotExist:
            return Response(code=1, errmsg='查无此人')

    @classmethod
    async def register(cls, user):
        """用户注册"""
        if await user_dao.has_user(username=user.username, mobile=user.mobile):
            return Response(code=400, errmsg='用户已存在')
        user.password = get_password_hash(user.password)
        user = await user_dao.create(user)
        return Response(data={"id": user.id, "username": user.username,
                              "token": create_access_token(user.id)
                              }
                        )

    @classmethod
    async def login(cls, user):
        if obj := await user_dao.has_user(username=user.username, mobile=user.username):
            if verify_password(user.password, obj.get("password")):
                return Response(data={"id": obj.get("id"), "username": obj.get("username"),
                                      "token": create_access_token(obj.get("id"))
                                      }
                                )
        return Response(code=400, errmsg='账号或密码错误')

    @classmethod
    async def update_email(cls, obj, email):
        await user_dao.update_field(obj, **email.dict())
        return Response()

    @classmethod
    async def active_email(cls, token):
        user_id = payload_token(token)
        await user_dao.update_field(user_id, email_active=True)
        return Response()








